<template>
  <div class="login-main" v-loading="submitLoading">
    <login-title title="登录"/>
    
    <div class="flex-row">
        <img src="~@/assets/login/icon_settings.svg" class="back-btn" @click="showLoginPage('desktop')" />
    </div>      
    <form class="form" @submit.prevent="submit">


      <div class="flex-row" id="login-home">
        <div class="login-logo">
          <img alt="electron" class="logo_icon" src="~@/assets/login//logo-electron.svg" />
          <img alt="electron-egg" class="logo_icon" src="https://www.kaka996.com/img/logo.png" />
          <img alt="antdv" class="logo_icon" src="https://next.antdv.com/assets/logo.1ef800a8.svg" />
        </div> 
      </div>

      <div class="flex-row">
          <button v-if="!loading" @click="login" type="button" class="btn btn-fill">
            <img src="@/assets/login/icon_wechat.svg" width="22" height="22" alt="wx-chat"> 
            扫码进入 Eletron-AntDV
          </button>
          <button v-else type="button" class="btn btn-fill">
            {{ loginText }} 
          </button>      
      </div>
      <div class="flex-row">
                   
      </div>
    <div class="flex-row">
      <div class="gap-text">  其它登录方式 </div>
    </div>
    <div class="flex-row">
        <button type="button" class="btn btn-outline" @click="showLoginPage('mobile')">
          <img src="~@/assets/login/icon_mobile.svg" width="25" height="25" alt="mobile" />
          手机
        </button>
        <button type="button" class="btn btn-outline" @click="showLoginPage('key')">
          <img src="~@/assets/login/icon_key.svg" width="25" height="25" alt="key" />
          密钥
        </button>
    
       
    </div> 

    <div class="flex-row agree">
        <label class="checkbox span" for="agree">
          <input type=checkbox name="agree">          
          我已阅读并同意 <a @click="openExternal('https://gitee.com/user-terms')" target="_blank">《隐私政策》</a>和<a  @click="openExternal('https://gitee.com/terms')" target="_blank">《服务协议》</a></label>
        
    </div>
    </form>
    
  </div> 
</template>

<script>
import LoginTitle from '@/components/bar/LoginTitle.vue';
import { ipcApiRoute } from '@/api/main';
import { ipc,isEE } from '@/utils/ipcRenderer';
import { message } from 'ant-design-vue';


export default {
  components: {
    LoginTitle
  },
  data() {
    return {
      loading: false, 
      loginText: '正在登陆......',
      regState: false,
      submitLoading: false,
      loginObj: {
        username: '',
        password: '',
        affirmPassword: ''
      },
      userData:[],
    }
  },

  beforeMount() {
     this.checkSetting();   
  },

  mounted() {
      
  },

  methods: {

    //这里可以检测一下软件设置，
    //比如：是否需要登录，直接跳转路由，或者是否需要注册账号等逻辑
    async checkSetting(){
      if (isEE) {
        await ipc.invoke(ipcApiRoute.setting.getUserData).then((rep) => {         
          rep && rep.data && rep.data.forEach(item => {
            for (let key in item) {
              this.userData[key] = item[key];
              // console.log(`${key}`, item[key]);
            }
          });
        });
        
        console.log("startup", this.userData['startup']);
        if (this.userData['startup'] && this.userData['pages'] ){
          //如果【设置】中用户配置了 免登录进入，这里可以直接跳转的路由
          this.$router.push( this.userData['pages'] );
          // location.reload();
        }else{
          this.resize();
        }  

      } else {
        console.log("开发模式无法启动IPC通信服务，元数据无法读取");
      }
    },
    resize(){
       isEE ?ipc.invoke(ipcApiRoute.window.panelLogin,{width: 400, height: 580 }).then(r => {
          console.log("跳转到登录页面")
        }):console.log("开发环境跳转");        
    },
    login() {
         this.loading = true;
         //需要自己完成登录或者授权逻辑
         setTimeout(() => {            
            isEE ?ipc.invoke(ipcApiRoute.window.panelMain, {width: 1140, height: 650}).then(r => {
              console.log("登录页跳转到演示页面");
              this.$router.push({ name: '桌面', params: {}});
            }):console.log("开发环境跳转")
         }, 100);
     },
 
    // 提交表单
    submit() {
      // 校验逻辑
      if (!this.loginObj.username || !this.loginObj.password) {
        this.$message({
          message: '请输入完整的账户信息！',
          type: 'info'
        })
        return
      }
      if (this.regState && this.loginObj.password !== this.loginObj.affirmPassword) {
        this.$message({
          message: '两次输入的密码不一致！',
          type: 'error'
        })
        return
      }
      this.submitLoading = true

      setTimeout(() => {
        this.$router.push('/state')
        const screenWidth = window.screen.width
        const screenHeight = window.screen.height

        window.ipcRenderer.send('toMain', {
          username: this.loginObj.username,
          token: '',
          screenWidth: screenWidth,
          screenHeight: screenHeight
        })
        this.submitLoading = false
      }, 1000)
    },
    
    showLoginPage(type) {
        let args= {
          type: 'web',
          content: 'https://www.bilibili.com/',
          windowName: 'window-web',
          windowTitle: 'bilibili',
          isModal: false,
        };
      if ('mobile' === type) {      
        this.$router.push('/login/mobile')
        
      } else if ('key' === type) {
        console.log("key login page");
        this.$router.push('/login/key');
        
      } else {
        console.log("other page");
        message.info('登陆前设置，根据需求自行完成',8)       
      }
    },

    
    // 打开外部链接的函数
    openExternal(url) {     
      //如果启用了上下文隔离( ontextIsolation: true), Electron 13+版本设置默认是启用的。
      //需要设置preload，通过contextBridge暴露的electron对象，及暴露的openExternal方法。
      if (window.electron && window.electron.openExternal) {
        window.electron.openExternal(url).then(() => {
          message.info('启用上下文隔离，需设置preload暴露electron.openExternal方法打开',8);
        }).catch((error) => {
          console.error('打开网页时出错:', error);
        });
      } else {
        //如果不启用上下文隔离( ontextIsolation: false)，则渲染进程中可直接使用electron对象调用openExternal方法。
        const { shell } = require('electron');
        if (shell.openExternal) { // 确保electron版本支持该方法
          shell.openExternal(url).then(() => {
            message.info('未启用上下文隔离，直接使用electron对象调用openExternal打开',8);
          }).catch((error) => {
            console.error('打开网页时出错:', error);
          });
        } else { 
          message.error('非EE环境，不支持openExternal打开默认浏览器', 8)
          window.open(url);
        }
      }
    },
    

  }
}
</script>

<style>
@import './index.css';

#app{background-color:#efefef;}
.el-loading-spinner .path {
  stroke: #151717 !important;
}
.el-loading-mask {
  border-radius: 20px !important;
  width: 410px !important;
}
.agree a{
  color:blue;
}

</style>
